// 描述用户相关信息及其权限
const Seller = require('../model/Seller');
const Buller = require('../model/Buller');

const setting = require('../setting');

const auth = {
    // 封装生成cookie的代码
    create_cookie: function(user, res) {
        // 设置cookie信息  --- 对cookie进行再次加密
        let auth_token = `${user._id}asd`;

        res.cookie(setting.auth_cookie_name, auth_token, {
            signed: true,
            maxAge: 1000 * 60 * 6 * 24 * 30,
            path: '/'
        })

    },
    create_cookie_buller: function(user, res) {
        // 设置cookie信息  --- 对cookie进行再次加密
        console.log(user._id)
        let auth_token = `${user._id}asd`;

        res.cookie(setting.user_cookie_name, auth_token, {
            signed: true,
            maxAge: 1000 * 60 * 6 * 24 * 30,
            path: '/'
        })

    },
    // 封装生成session的代码
    // 通过浏览器端返回的cookie信息生成session
    // req.signedCookies 获取被签名的cookie
    create_session: function(req, res, next) {
        // 判断是否有用户登录 req.session.user
       if(req.session.seller){
           console.log('seller已存在');
           next();
       }else{


           let auth_token = req.signedCookies[setting.auth_cookie_name];
           // console.log(auth_token);
           if(!auth_token) {
               return next();
           }
           // split()将字符串分割成数组
           let auth = auth_token.split('asd');
           // console.log(auth);
           let user_id = auth[0];
           Seller.getSellerById(user_id, (err, user) => {
               if (err) {
                   return next();
               }


               //查找通知消息的个数


               req.session.seller = user;
               req.session.isLogin = true;
               next();
           })



       }
    },
    create_session_buller:function(req, res, next) {
        if(req.session.buller){
            console.log('buller已存在');
            next();
        }else{


            let auth_token2 = req.signedCookies[setting.user_cookie_name];
            // console.log(auth_token);
            if(!auth_token2) {
                return next();
            }
            // split()将字符串分割成数组
            let auth2 = auth_token2.split('asd');

            let user_id2 = auth2[0];
            Buller.getBullerById(user_id2, (err, user2) => {
                if (err) {
                    return next();
                }


                req.session.buller = user2;
                req.session.bullerLogin = true;
                next();

            })

        }





    }



}



module.exports = auth;